package com.example.coffeeseller_2.model.helper;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;

import com.example.coffeeseller_2.model.beans.DealRecorder;
import com.example.coffeeseller_2.model.listenner.MsgTransListener;
import com.example.coffeeseller_2.model.listenner.OnTradeListenner;
import com.example.coffeeseller_2.model.model.TradeMsgRequest;
import com.example.coffeeseller_2.model.parse.ParseRQMsg;
import com.example.coffeeseller_2.model.parse.PayResult;
import com.example.coffeeseller_2.utils.MyLog;
import com.example.coffeeseller_2.utils.QRCodeUtil;

import static com.example.coffeeseller_2.model.factory.PayState.NO_PAY;
import static com.example.coffeeseller_2.model.factory.PayState.PAYED;
import static com.example.coffeeseller_2.model.factory.PayState.PAYING;

/**
 * Created by WH on 2018/8/11.
 */

public class Trade {

    private static String TAG = "Trade";
    private static Trade instance;
    private boolean isVilide = false;//当前类无效，true：表示有效
    private long timeLimit = 30 * 1000;
    private Context context;
    private MsgTransListener mMsgTransListener;
    private OnTradeListenner onTradeListenner;
    private TradeMsgRequest tradeMsgRequest;
    private Thread timeThread;
    private int curPayState = NO_PAY;
    private boolean hasPayError = false;
    private long saomaSuccessTime;
    private long firstRequestQrCode;//第一次请求二维码的时间

    public static Trade getInstance() {
        if (instance == null) {
            instance = new Trade();
        }
        return instance;
    }

    private Trade() {

    }

    public void init(Context context, MsgTransListener mMsgTransListener, OnTradeListenner onTradeListenner) {
        this.context = context;
        this.onTradeListenner = onTradeListenner;
        this.mMsgTransListener = mMsgTransListener;
        tradeMsgRequest = new TradeMsgRequest();
        isVilide = true;
    }

    public void clear() {
        timeThread = null;
        curPayState = NO_PAY;
        hasPayError = false;
        saomaSuccessTime = 0;
        isVilide = false;
    }

    /*
    * 请求二维码
    * */
    public void requestQrCode() {
        MyLog.W(TAG, "request qr code");
        tradeMsgRequest.requestQRCode(mMsgTransListener);
        timeThread = null;
    }

    public void closeTrade(String order) {
        MyLog.W(TAG, "close order");

        tradeMsgRequest.closeOrder(order);
        stopTaskCheckPay();
    }

    /*
    * 循环检测支付结果
    * */
    public void beginTaskCheckPay() {
        MyLog.W(TAG, "check pay");

        tradeMsgRequest.beginTaskCheckPay(mMsgTransListener);
    }

    public void stopTaskCheckPay() {
        tradeMsgRequest.stopTaskCheckPay();
    }

    /*
    * 开启扫码后30秒的倒计时倒计时
    * */
    private void startCountDown() {

        if (timeThread != null) {
            return;
        }
        hasPayError = false;

        if (timeThread == null) {
            timeThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (!hasPayError) {
                        if (System.currentTimeMillis() - saomaSuccessTime > timeLimit) {

                            if (DealRecorder.getInstance().getPayState() != PAYED) {
                                if (onTradeListenner != null) {
                                    onTradeListenner.payingErr();
                                }
                            }
                            hasPayError = true;
                        }
                    }
                    timeThread = null;
                    // stopTaskCheckPay();
                }
            });
        }
        timeThread.start();

    }

    private void stopCountDown() {
        if (timeThread != null) {
            timeThread = null;
        }
    }

    /*
    * 处理接收到的消息
    * */
    public void dealMsgArrived(Object msg) {
        if (msg != null) {

            if (msg instanceof ParseRQMsg) {

                ParseRQMsg parseRqMsg = (ParseRQMsg) msg;
                getQrMsg(parseRqMsg);

                MyLog.d(TAG, "qrcode come " + parseRqMsg.getQrCode());

            }
            if (msg instanceof PayResult) {
                PayResult aMsg = (PayResult) msg;
                getPayMsg(aMsg);

                MyLog.d(TAG, "payResult come !");
            }
        } else {
            if (tradeMsgRequest.mCurRequest == TradeMsgRequest.REQUEST_QR_CODE) {
                //  setQR_Code(null);  是否自动再次请求还是让别人点击出现
                MyLog.W(TAG, "no message come in reqQR");
            }
            if (tradeMsgRequest.mCurRequest == TradeMsgRequest.REQUEST_CHECK_PAY) {
                MyLog.W(TAG, "check pay msg is null");
            }

        }
    }


    /*
    * 根据返回信息，设置二维码
    * */
    private void getQrMsg(ParseRQMsg parseRqMsg) {

        MyLog.W(TAG, "QR msg come now going to deal this msg");

        DealRecorder.getInstance().setOrder(parseRqMsg.getTradeCode());

        final String price = parseRqMsg.getPrice();
        MyLog.d(TAG, "getPrice = " + parseRqMsg.getPrice());
        DealRecorder.getInstance().setPrice(parseRqMsg.getPrice());

        if (parseRqMsg == null) {
            MyLog.d(TAG, "parseRqMsg is empty");
            if (onTradeListenner != null) {
                onTradeListenner.getQrBitmap(null);

                if (System.currentTimeMillis() - firstRequestQrCode < 110 * 1000 && isVilide) {
                    requestQrCode();
                }
            }
            return;
        }
        DealRecorder.getInstance().setCupNum(parseRqMsg.getCupNum());

  /*      QRMaker mQrMaker = new QRMaker();
        Bitmap bitmap = mQrMaker.createBitmap(parseRqMsg.getQrCode(), 350, 350);*/

        if (TextUtils.isEmpty(parseRqMsg.getQrCode()) || TextUtils.equals(parseRqMsg.getQrCode(), "null")) {

            if (onTradeListenner != null) {
                onTradeListenner.getQrBitmap(null);
            }
        }

        Bitmap bitmap = QRCodeUtil.createQRImage(parseRqMsg.getQrCode(), 350, 350);

        if (onTradeListenner != null) {
            onTradeListenner.getQrBitmap(bitmap);
        }

        if (DealRecorder.getInstance().getPayState() != PAYED
                && !TextUtils.isEmpty(DealRecorder.getInstance().getOrder())) {

            tradeMsgRequest.beginTaskCheckPay(mMsgTransListener);
        }

        MyLog.W(TAG, "dealOrder = " + DealRecorder.getInstance().getOrder());
    }

    /*
 * 接收支付检查结果，并处理
 * */
    private void getPayMsg(PayResult msg) {
        MyLog.d(TAG, "msg= " + msg);

        if (DealRecorder.getInstance().getPayState() == PAYED) {
            MyLog.d(TAG, "DealRecorder.getInstance().getPayState()  = " + DealRecorder.getInstance().getPayState());
            return;
        }

        if (!TextUtils.equals(DealRecorder.getInstance().getOrder(), msg.getTradeCode())) {
            Log.d(TAG, "cur order= " + DealRecorder.getInstance().getOrder() + " , mqtt order =" + msg.getTradeCode());
            return;
        }
        MyLog.d(TAG, "msg.getPayResult()= " + msg.getPayResult());
        if (curPayState == NO_PAY) {
            if (msg.getPayResult() == PAYING) {

                if (DealRecorder.getInstance().getPayState() == PAYING) {
                    return;
                }

                Log.d(TAG, "curPayState == " + PAYING);
                MyLog.W(TAG, "check pay result is paying ");

                if (onTradeListenner != null) {
                    onTradeListenner.isPaying();
                }
                curPayState = PAYING;
                saomaSuccessTime = System.currentTimeMillis();
                startCountDown();

            }
            if (msg.getPayResult() == PAYED) {

                if (DealRecorder.getInstance().getPayState() == PAYED) {
                    return;
                }

                MyLog.W(TAG, "check pay result is payed ");

                if (onTradeListenner != null) {
                    onTradeListenner.hasPayed();
                    stopCountDown();
                }
                curPayState = PAYED;
                Log.d(TAG, "curPayState == " + PAYED);
            }

            MyLog.W(TAG, "check pay result is not pay ");
        }
        if (curPayState == PAYING) {

            if (msg.getPayResult() == PAYED) {

                if (DealRecorder.getInstance().getPayState() == PAYED) {
                    return;
                }
                MyLog.W(TAG, "check pay result is payed ");

                if (onTradeListenner != null) {
                    onTradeListenner.hasPayed();
                    stopCountDown();
                }
                curPayState = PAYED;
                Log.d(TAG, "curPayState == " + PAYED);
            }

        }
    }


}
